package richbar.com.richbar.activity.product;

import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.base.BaseActivity;
import com.common.util.ToastUtil;
import com.okhttp.network.HttpUtils;
import com.okhttp.network.MyGson;
import com.tencent.mm.opensdk.modelpay.PayReq;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import richbar.com.richbar.R;
import richbar.com.richbar.activity.me.ManageGoodsAddressAc;
import richbar.com.richbar.adapter.shopping.ShoppingsAdapter;
import richbar.com.richbar.base.BaseApplication;
import richbar.com.richbar.bean.AddressResult;
import richbar.com.richbar.bean.Bean;
import richbar.com.richbar.bean.GoodsInfoResult;
import richbar.com.richbar.bean.OrderBean;
import richbar.com.richbar.bean.SelectPayKindBean;
import richbar.com.richbar.bean.ShopCartListBean;
import richbar.com.richbar.help.Constants;
import richbar.com.richbar.help.TitleHelp;
import richbar.com.richbar.util.LoadingDialog;
import richbar.com.richbar.util.NetWorkUtil;
import richbar.com.richbar.util.Util;
import richbar.com.richbar.view.NoExpandableListView;
import richbar.com.richbar.view.dialog.MaYiInputDialog;
import richbar.com.richbar.view.pop.CommonBottomPop;
import richbar.com.richbar.view.pop.SelectAddressPop;


/**
 * Created by Administrator on 2018/12/11.
 */

public class FirmOrderShopCartAc extends BaseActivity {
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.tel)
    TextView tel;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.pay_way)
    TextView payWay;
    @BindView(R.id.distribution_way)
    TextView distributionWay;
    @BindView(R.id.payment_way)
    TextView paymentWay;
    @BindView(R.id.invoice)
    TextView invoice;
    @BindView(R.id.message)
    EditText message;
    @BindView(R.id.goods_price)
    TextView goodsPrice;
    @BindView(R.id.freight)
    TextView freight;
    @BindView(R.id.beans)
    TextView beans;
    @BindView(R.id.voucher)
    TextView voucher;
    @BindView(R.id.gold)
    TextView gold;
    @BindView(R.id.pay_money_left)
    TextView payMoneyLeft;
    @BindView(R.id.pay_money_right)
    TextView payMoneyRight;
    @BindView(R.id.body)
    LinearLayout body;
    @BindView(R.id.ex_listView)
    NoExpandableListView expandableListView;
    private GoodsInfoResult.DataEntity.InfoEntity bean;
    private AddressResult.AddressBean addressBean;
    private String addrid = "";//地址ID
    private ShoppingsAdapter adapter;
    List<ShopCartListBean.DataBean.ListBean> groups = new ArrayList<>();
    List<List<ShopCartListBean.DataBean.ListBean.GoodsBean>> childs = new ArrayList<>();
    private LoadingDialog dialog;
    private String shipping = "1";
    private String pay_method = "";
    private String str_invoice = "1";
    private String str_remark = "";
    private String amount = "";
    private String balance = "";
    private String score = "";
    private String coupon = "";
    private String invoice_name = "";
    private String invoice_type = "";
    private String goods = "";
    private String str_address = "";
    public static String Orderid = "";
    public static boolean bln_kind = false;//false 购物车订单 true 个人中心充值

    @Override
    public int initLayout() {
        return R.layout.ac_firms_order;
    }

    @Override
    public void initTitle() {
        new TitleHelp(this).setTitle("确认订单");
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        dialog = new LoadingDialog(FirmOrderShopCartAc.this, 0);
        getData();
        adapter = new ShoppingsAdapter(FirmOrderShopCartAc.this, groups, childs, payMoneyLeft);
        expandableListView.setAdapter(adapter);
    }

    private void getData() {
        dialog.show();
        NetWorkUtil.getCarList(BaseApplication.uid, Util.md5(), new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String data) {
                dialog.dismiss();
                final ShopCartListBean shopCartListBean = MyGson.getInstance().fromJson(data, ShopCartListBean.class);
                if (shopCartListBean.getData().getList().size() > 0) {
                    for (int i = 0; i < shopCartListBean.getData().getList().size(); i++) {
                        groups.add(shopCartListBean.getData().getList().get(i));
                        List<ShopCartListBean.DataBean.ListBean.GoodsBean> list = new ArrayList<ShopCartListBean.DataBean.ListBean.GoodsBean>();
                        for (int j = 0; j < shopCartListBean.getData().getList().get(i).getGoods().size(); j++) {
                            if (shopCartListBean.getData().getList().get(i).getGoods().get(j).getGoods_select().equals("1")) {
                                list.add(shopCartListBean.getData().getList().get(i).getGoods().get(j));
                                goods = goods + shopCartListBean.getData().getList().get(i).getGoods().get(j).getCart_id() + ",";
                            }
                        }
                        childs.add(list);

                    }
                    if (groups.size() > 0) {
                        for (int i = 0; i < groups.size(); i++) {
                            expandableListView.expandGroup(i);
                        }
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    expandableListView.setVisibility(View.GONE);

                }
                payMoneyLeft.setText(shopCartListBean.getData().getTotalPrice() + "");
                goodsPrice.setText(shopCartListBean.getData().getTotalPrice() + "");
                amount = shopCartListBean.getData().getTotalPrice() + "";
                if (shopCartListBean.getData().getIs_def_address().equals("1")) {//设置收货地址
                    name.setText(shopCartListBean.getData().getDef_address().getPerson());
                    tel.setText(shopCartListBean.getData().getDef_address().getMobile());
                    address.setText(shopCartListBean.getData().getDef_address().getAddress());
                    addrid = shopCartListBean.getData().getDef_address().getId();
                    str_address=shopCartListBean.getData().getDef_address().getAddress();
                }
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
                dialog.dismiss();
                ToastUtil.showToast(FirmOrderShopCartAc.this, msg);
            }
        });

    }

    private void showAddress() {
        SelectAddressPop pop = new SelectAddressPop(FirmOrderShopCartAc.this);
        pop.show(body, new SelectAddressPop.Callback() {
            @Override
            public void onAddressId(AddressResult.AddressBean bean) {
                addressBean = bean;
                name.setText(bean.getName());
                tel.setText(bean.getMobile());
                address.setText(bean.getProvince() + bean.getCity() + bean.getAddress());
                addrid = bean.getId();
//                deliveryRange.setText(bean.getAddress());
            }

            @Override
            public void onSelectOtherAddress() {

            }
        });
    }

    private void setData() {
        name.setText(bean.getGoods_name());
        String goodsPrice = bean.getGoods_price();

    }

    @OnClick({R.id.relative, R.id.pay_way_body, R.id.distribution_way_body, R.id.payment_way_body, R.id.invoice_body, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.add:
                break;
            case R.id.relative://选择收货地址
                if(!str_address.equals(""))
                showAddress();
                else
                start(ManageGoodsAddressAc.class);
                break;
            case R.id.sub:

                break;
            case R.id.pay_way_body:
                showPay();
                break;
            case R.id.distribution_way_body:
                showDelivery();
                break;
            case R.id.payment_way_body:
                showPayment();
                break;
            case R.id.invoice_body:
                showInvoice();
                break;
            case R.id.submit:
                str_remark = message.getText().toString();
                if (!str_address.equals("")) {
                    dialog.show();
                    NetWorkUtil.subitOrders(BaseApplication.uid, addrid, amount, str_remark, shipping, balance, pay_method, score, coupon, str_invoice, invoice_name,
                            invoice_type, "2", goods, new HttpUtils.HttpCallback() {
                                @Override
                                public void onSuccess(String data) {
                                    dialog.dismiss();
                                    final OrderBean orderBean = MyGson.getInstance().fromJson(data, OrderBean.class);
                                    if (orderBean.getCode() == 200) {
                                        sendPayRequest(orderBean);
                                        finish();
                                        Orderid = orderBean.getData().getOrderid();
                                        bln_kind = true;
                                    }
                                }

                                @Override
                                public void onError(String msg) {
                                    dialog.dismiss();
                                    super.onError(msg);
                                    ToastUtil.showToast(FirmOrderShopCartAc.this, msg);
                                }
                            });
                } else {
                    start(ManageGoodsAddressAc.class);
                    ToastUtil.showToast(FirmOrderShopCartAc.this, "请选择收货地址");
                }

                break;
        }
    }

    /**
     * 调用微信支付
     */
    public void sendPayRequest(OrderBean orderBean) {
        try {
            PayReq req = new PayReq();
            req.appId = Constants.APP_ID;
            req.partnerId = orderBean.getData().getPayOption().getPartnerid();
            req.prepayId = orderBean.getData().getPayOption().getPrepayid();
            req.nonceStr = orderBean.getData().getPayOption().getNoncestr();
            req.timeStamp = orderBean.getData().getPayOption().getTimestamp();
            req.packageValue = orderBean.getData().getPayOption().getPackageX();
            req.sign = orderBean.getData().getPayOption().getSign();
            req.extData = "app data"; // optional
            Toast.makeText(FirmOrderShopCartAc.this, "调起微信支付", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            BaseApplication.iwxapi.sendReq(req);

        } catch (Exception e) {
            Log.e("PAY_GET", "异常：" + e.getMessage());
            Toast.makeText(FirmOrderShopCartAc.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();

        }
    }

    private void showPay() {
        CommonBottomPop pop = new CommonBottomPop(this);
        List<Bean> data = new ArrayList<>();
        data.add(new Bean("1", "微信"));
        pop.show(payWay, "支付方式", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                payWay.setText(bean.getValue());
            }
        });

    }

    private void showPayment() {
        final CommonBottomPop pop = new CommonBottomPop(this);
        final List<Bean> data = new ArrayList<>();
        data.add(new Bean("1", "全部现金"));
        data.add(new Bean("2", "全部金币"));
        data.add(new Bean("3", "待返金额"));
        data.add(new Bean("4", "已返金额"));
        data.add(new Bean("5", "蚂蚁豆支付"));
        data.add(new Bean("6", "蚂蚁券支付"));
        pop.show(paymentWay, "付款方式", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                dialog.show();
                NetWorkUtil.getSelectPayKind(bean.getId(), new HttpUtils.HttpCallback() {
                    @Override
                    public void onSuccess(String data) {
                        dialog.dismiss();
                        final SelectPayKindBean selectPayKindBean = MyGson.getInstance().fromJson(data, SelectPayKindBean.class);
                        if (selectPayKindBean.getCode() == 200) {
                            paymentWay.setText(bean.getValue());
                            pay_method = bean.getId();
                            beans.setText("");
                            voucher.setText("");
                            if (bean.getId().equals("5")) {
                                score = selectPayKindBean.getData().getCurrent() + "";
                                beans.setText("-¥" + selectPayKindBean.getData().getCurrent());

                            }
                            if (bean.getId().equals("6")) {
                                coupon = selectPayKindBean.getData().getCurrent() + "";
                                voucher.setText("-¥" + selectPayKindBean.getData().getCurrent());
                            }


                            pop.click(new CommonBottomPop.OnItemOnClickListener() {
                                @Override
                                public void onItemClick(int pos) {
                                    switch (pos){
                                        case 4:
                                            showMaYiBean(score);
                                            break;
                                        case 5:
                                            showMaYiCoupon(coupon);
                                            break;
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        super.onError(msg);
                        dialog.dismiss();
                    }
                });
            }

            private void showMaYiBean(String content) {

                MaYiInputDialog dialog = new MaYiInputDialog();
                dialog.show(FirmOrderShopCartAc.this, "本商品最多使用5个蚂蚁豆\n您拥有" +content+ "个蚂蚁豆", new MaYiInputDialog.Callback() {
                    @Override
                    public void onBesure(String num) {

                    }
                });
            }

            private void showMaYiCoupon(String content) {
                MaYiInputDialog dialog = new MaYiInputDialog();
                dialog.show(FirmOrderShopCartAc.this, "本商品最多使用5个蚂蚁券\n您拥有" +content+ "个蚂蚁券", new MaYiInputDialog.Callback() {
                    @Override
                    public void onBesure(String num) {

                    }
                });
            }
        });


    }

    private void showDelivery() {
        CommonBottomPop pop = new CommonBottomPop(this);
        List<Bean> data = new ArrayList<>();
        data.add(new Bean("1", "在线发货"));
        data.add(new Bean("2", "平台发货"));
        pop.show(distributionWay, "配送方式", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                distributionWay.setText(bean.getValue());
                shipping = bean.getId();
            }
        });

    }

    private void showInvoice() {
        CommonBottomPop pop = new CommonBottomPop(this);
        List<Bean> data = new ArrayList<>();
        data.add(new Bean("2", "开具发票"));
        data.add(new Bean("1", "不开发票"));
        pop.show(invoice, "发票", data, new CommonBottomPop.Callback() {
            @Override
            public void callback(final Bean bean) {
                invoice.setText(bean.getValue());
                str_invoice = bean.getId();
            }
        });

    }
}
